#include "qdateproperty.h"


#include <QDateEdit>

QDateProperty::QDateProperty(SHAREDLIB::QAbstractProperty *parent):
    SHAREDLIB::QAbstractProperty(parent)
{
    connect(this,SIGNAL(showValueChanged()),this,SLOT(value_changed()));
}

void QDateProperty::valueXML(QXmlStreamWriter *w)
{
    QDate dt=getValue().toDate();
    w->writeAttribute("year",QString::number(dt.year()));
    w->writeAttribute("month",QString::number(dt.month()));
    w->writeAttribute("day",QString::number(dt.day()));
}

void QDateProperty::parserXML(QXmlStreamReader *r)
{
    QDate dt;

    int year,month,day;
    year=2000;
    month=1;
    day=1;

    foreach(const QXmlStreamAttribute &attribute,r->attributes())
    {
        if(attribute.name().toString()=="year")
        {
            year=attribute.value().toString().toInt();
        }
        else if(attribute.name().toString()=="month")
        {
            month=attribute.value().toString().toInt();
        }
        else if(attribute.name().toString()=="day")
        {
            day=attribute.value().toString().toInt();
        }
    }

    for(bool finished=false;!finished && !r->hasError();)
    {
        switch(r->readNext())
        {
        case QXmlStreamReader::StartElement:
            break;
        case QXmlStreamReader::EndElement:
            finished=true;
            break;
        default:
            break;
        }
    }

    dt.setYMD(year,month,day);
    setValue(dt);
}

QWidget* QDateProperty::getEditor()
{
    if(attribute("editabled").toBool())
    {
        QDateEdit *ti=new QDateEdit;
        connect(ti,SIGNAL(dateChanged(QDate)),this,SLOT(editor(QDate)));
        m_editor=ti;
    }
    return QAbstractProperty::getEditor();
}

void QDateProperty::editor(const QDate &date)
{
    QDate v=getValue().toDate();
    if(v!=date)
    {
        setModified(true);
        setSignalValue(date);
    }
}

QString QDateProperty::valueText()
{
    QDate dt=getValue().toDate();
    return QString("%1-%2-%3").arg(dt.year(),4).arg(dt.month(),2).arg(dt.day(),2);
}

void QDateProperty::value_changed()
{
    if(m_editor!=NULL)
    {
        ((QDateEdit*)m_editor)->setDate(m_value.toDate());
    }
}
